import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LearnView from '../views/LearnView.vue'
import PracticeView from '../views/PracticeView.vue'
import ProgressView from '../views/ProgressView.vue'
import NProgress from 'nprogress'
// 引入用户store
import { useUserStore } from '@/stores'

// 配置nprogress
NProgress.configure({
  easing: 'ease', // 缓冲动画类型，可选值如'ease'、'linear'等
  speed: 1000, // 动画速度，单位为毫秒
  trickleSpeed: 200, // 每次进度条步进的速度，单位为毫秒
  showSpinner: false, // 是否显示环形进度动画
  minimum: 0.2, // 设置开始时最低百分比
})

// 创建路由实例
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      meta: {
        title: '数学学习可视化 - 首页',
      },
    },
    {
      path: '/learn',
      name: 'learn',
      component: LearnView,
      meta: {
        title: '学习中心',
      },
    },
    {
      path: '/practice',
      name: 'practice',
      component: PracticeView,
      meta: {
        title: '练习中心',
      },
    },
    {
      path: '/progress',
      name: 'progress',
      component: ProgressView,
      meta: {
        title: '学习进度',
      },
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue'),
      meta: {
        title: '用户登录',
      },
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/RegisterView.vue'),
      meta: {
        title: '用户注册',
      },
    },
    // 404页面
    {
      path: '/:pathMatch(.*)*',
      name: 'not-found',
      component: () => import('../views/NotFoundView.vue'),
      meta: {
        title: '页面未找到',
      },
    },
  ],
})

// 路由守卫 - 设置页面标题
router.beforeEach((to, from, next) => {
  // console.log(to, from, 'to, from--路由守卫')
  const userStore = useUserStore()
  if (to.path === '/login' || to.path === '/register') {
    if (userStore.isAuthenticated) {
      next('/')
    } else {
      next()
    }
  }
  NProgress.start()
  if (to.meta.title) {
    document.title = to.meta.title as string
  }
  next()
})

router.afterEach(() => {
  NProgress.done()
})

export default router
